<template>
  <view class="container">
    <view class="user-info">
      <view class="user-picture">
        <button class="button-reset" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image class="avatar" :src="userInfo.avatarUrl||'/static/logo.png'"> </image>
        </button>
      </view>
      <view class="user-name">
        <!-- 昵称显示区域 -->
        <view class="username" @click="openNicknameModal" v-if="status">{{ userInfo.nickName || '点击设置昵称' }}
        </view>
        <view class="username" @click="toLogin" v-if="!status">{{ userInfo.nickName || '登录/注册' }}</view>
        <!--  <view class="vip" @click="toVip">
          成为会员
        </view> -->
        <uni-icons type="right" size="30"></uni-icons>
        <!-- 弹窗 -->
        <modal v-if="showNicknameModal" @confirm="submitNickname" @cancel="showNicknameModal=false">
          <input type="nickname" name="nickName" v-model="nickname" @blur="bindblur" placeholder="请输入昵称"
            @input="bindinput" />
        </modal>
      </view>

      <!--  <view class="user-name">
        <form @submit="formSubmitInfoTap">
          <view class="form">
            <input class="username" type="nickname" name="nickName" placeholder="请输入昵称" v-model="userInfo.nickName"
              @input="onNicknameInput" />
            <button class="submitBtn" v-if="isConfirmButtonVisible" type="primary" form-type="submit"
              size="large">确认</button>
          </view>
        </form>
      </view> -->

    </view>
    <!-- 	<view class="wallet">
			<view class="wallet-item" @click="goToPointsPage">
				<text class="wallet-value">{{ points.pointsNumber+points.commissionpoints ||0 }}</text>
				<text class="wallet-title">积分</text>
			</view>
			<view class="wallet-item" @click="goToCouponPage">
				<text class="wallet-value">{{ coupons.length || 0 }}</text>
				<text class="wallet-title">优惠券/码</text>
			</view>
			<view class="wallet-item" @click="toQR">
				<text class="wallet-value">{{ userInfo.integral ||1}}</text>
				<text class="wallet-title">分享码</text>
			</view>
		</view> -->
    <!-- <view class="order-section">
			<view class="order-header">
				<text class="section-title">我的订单</text>
				<text class="view-all" @click="goToOrderPage('all')">查看全部</text>
			</view>
			<view class="order-types">
				<view class="order-type" @click="goToOrderPage('pendingPayment')">
					<uni-icons class="order-icon" type="wallet" size="30"></uni-icons>
					<text class="order-type-title">待付款</text>
					<text class="order-type-number">{{ userInfo.pendingPayment }}</text>
				</view>
				<view class="order-type" @click="goToOrderPage('pendingDelivery')">
					<uni-icons class="order-icon" type="compose" size="30"></uni-icons>
					<text class="order-type-title">待发货</text>
					<text class="order-type-number">{{ userInfo.pendingDelivery }}</text>
				</view>
				<view class="order-type" @click="goToOrderPage('pendingReceipt')">
					<uni-icons class="order-icon" type="checkbox-filled" size="30"></uni-icons>
					<text class="order-type-title">待收货</text>
					<text class="order-type-number">{{ userInfo.pendingReceipt }}</text>
				</view>
				<view class="order-type" @click="goToOrderPage('afterSale')">
					<uni-icons class="order-icon" type="help" size="30"></uni-icons>
					<text class="order-type-title">售后</text>
					<text class="order-type-number">{{ userInfo.afterSale }}</text>
				</view>
			</view>
		</view> -->
    <view class="function-section">
      <!-- <view class="function-item" @click="goToAddressPage">
        <uni-icons class="function-icon" type="location-filled" size="30"></uni-icons>
        <text class="function-title">收货地址</text>
      </view> -->

      <view class="function-item">
        <uni-icons class="function-icon" type="chat" size="30"></uni-icons>
        <button class="function-title" open-type="contact" bindcontact="handleContact"
          session-from="sessionFrom">咨询客服</button>
      </view>
      <view v-if="role=='admin'" class="function-item" @click="goToShopPage">
        <uni-icons class="function-icon" type="gear-filled" size="30"></uni-icons>
        <button class="function-title">我的店铺</button>
      </view>
      <!-- 			<view class="function-item" @click="goToOder">
				<uni-icons class="function-icon" type="gear-filled" size="30"></uni-icons>
				<text class="function-title">我的订单</text>
			</view> -->
      <view class="function-item" @click="goToFootPrint">
        <uni-icons class="function-icon" type="gear-filled" size="30"></uni-icons>
        <button class="function-title">历史足迹</button>
      </view>
      <view class="function-item" @click="outLogin">
        <uni-icons class="function-icon" type="gear-filled" size="30"></uni-icons>
        <button class="function-title">退出登录</button>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    searchallorderlist,
    searchorderinfo
  } from '../../api/order/order.js';
  import {
    getcostomer
  } from '../../api/getcostomer/getcostomer.js';
  import {
    getpointscoupons
  } from '../../api/getpointscoupons/getpointscoupons.js';
  import {
    uploaduserimage,
    uploadusername
  }
  from '../../api/login/login.js'
  export default {
    data() {
      return {
        type: '',
        userInfo: {
          avatarUrl: '/static/logo.png',
          nickName: '',
          pendingPayment: 0,
          pendingDelivery: 0,
          pendingReceipt: 0,
          afterSale: 0,
          role: '',
        },
        status: false,
        points: {},
        coupons: {},
        showNicknameModal: false, // 控制弹窗显示
        nickname: '',
        userId: '',
        isConfirmButtonVisible: false // 控制确认按钮的显示
      };
    },




    methods: {
      //跳转到推广码
      toQR() {
        uni.navigateTo({
          url: '/pages/promotion/promotion',
        })
      },
      //跳转到成为会员
      toVip() {
        uni.navigateTo({
          url: '/pages/becomeVIP/becomeVIP',
        })
      },
      // 点击跳转到积分页面
      goToPointsPage() {
        // 使用 uni.navigateTo 跳转到积分页面
        uni.navigateTo({
          url: '/pages/points/points'
        });
      },
      // 点击跳转到优惠券页面
      goToCouponPage() {
        // 使用 uni.navigateTo 跳转到积分页面 
        uni.navigateTo({
          url: '/pages/coupon/coupon'
        });
      },
      goToShopPage() {
        uni.navigateTo({
          url: '/pages/myShop/myShop'
        });
      },
      goToFootPrint() {
        uni.navigateTo({
          url: '/pages/footprint/footprint'
        });
      },
      goToOder() {
        uni.navigateTo({
          url: '/pages/newOrder/newOrder'
        });
      },
      //修改昵称弹窗
      openNicknameModal() {
        this.showNicknameModal = true;
      },
      submitNickname() {
        // 处理用户提交的昵称
        let userInfoFromStorage = uni.getStorageSync('userInfo');
        const data = {
          virtualName: this.nickname,
          userId: userInfoFromStorage.userId
        }
        uploadusername(data).then(res => {
          //  console.log(res);
          this.userInfo.nickName = this.nickname;
        })
        //  console.log('提交的昵称:', this.nickname);

        this.showNicknameModal = false; // 关闭弹窗

        if (userInfoFromStorage) {
          userInfoFromStorage.nickName = this.nickname;
          uni.setStorageSync('userInfo', userInfoFromStorage);
        }
      },
      bindblur(e) {
        this.nickname = e.detail.value; // 获取微信昵称
      },
      bindinput(e) {
        this.nickname = e.detail.value;
      },
      // 获取选中的头像 URL
      onChooseAvatar(e) {
        const avatarUrl = e.detail.avatarUrl; // 获取选中的头像 URL
        if (avatarUrl) {

          let userInfoFromStorage = uni.getStorageSync('userInfo');
          if (!userInfoFromStorage) {
            this.toLogin()
            return;
          }
          this.userInfo.avatarUrl = avatarUrl; // 更新用户头像 URL
          //  console.log(avatarUrl)
          // 创建一个表单对象
          const formData = {
            userId: userInfoFromStorage.userId,

          };
          // 发送POST请求
          uni.uploadFile({
            url: 'https://shop.flowergk.com/shop/wxapplet/uploaduserimage', // 上传文件的URL
            filePath: avatarUrl,
            name: 'signatureImage', // 服务器接收文件的字段名
            formData: formData, // 非文件参数
            success: function(uploadFileRes) {
              //  console.log('文件上传成功：', JSON.parse( uploadFileRes.data).data.image);
              // this.userInfo.avatarUrl = JSON.parse( uploadFileRes.data).data.image;
              // this.$forceUpdate()

            },
            fail: function(err) {
              console.error('文件上传失败：', err);
            }
          });

          if (userInfoFromStorage) {
            userInfoFromStorage.avatarUrl = avatarUrl;
            uni.setStorageSync('userInfo', userInfoFromStorage);
          }
        }

      },
      onNicknameInput() {
        // 当昵称输入框有内容时显示确认按钮
        this.isConfirmButtonVisible = this.userInfo.nickName.trim() !== '';
      },


      toLogin() {
        uni.showModal({
          title: '登录/注册',
          content: '登录使用完整功能',
          showCancel: true,
          cancelText: '取消',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              uni.redirectTo({
                url: '/pages/login/login'
              })
            } else if (res.cancel) {
              return
            }
          },
        })
        return;
      },
      getUserInfo() {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo) {
          this.userInfo.nickName = '';
          this.userInfo.avatarUrl = '/static/logo.png';
          this.status = false;
          this.userInfo.pendingPayment = 0;
          this.userInfo.pendingDelivery = 0;
          this.userInfo.pendingReceipt = 0;
          this.userInfo.afterSale = 0;
          return
        }
        this.status = true;
        this.userInfo.nickName = userInfo.nickName;
        this.userInfo.avatarUrl = userInfo.avatarUrl;
        this.userId = userInfo.userId;
        this.role = userInfo.role;
        // this.searchorderinfo();
      },
      //查询订单信息
      searchorderinfo() {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo) {
          return
        }
        let openId = uni.getStorageSync('openid');
        searchorderinfo({
          openId: openId
        }).then(res => {
          this.userInfo.pendingPayment = res.data.data.statezero.length;
          this.userInfo.pendingDelivery = res.data.data.stateone.length;
          this.userInfo.pendingReceipt = res.data.data.statetwo.length;
          this.userInfo.afterSale = res.data.data.paystate.length;
        }).catch(res => {
          //  console.log(res.data);
        })
      },
      //退出登录
      outLogin() {
        if (!this.status) {
          uni.showToast({
            title: '请先登录',
            icon: 'none',
          })
          return
        }
        uni.showModal({
          title: '退出登录',
          content: '确认退出登录？',
          cancelText: '取消',
          confirmText: '确认',
          success(res) {

            if (res.confirm) {
              uni.clearStorageSync(); //清除所有缓存
              uni.switchTab({
                url: '/pages/index/index'
              })
            } else if (res.cancel) {
              return
            } else {
              return
            }
          }
        })

      },
      getOrderItems() {
        let openId = uni.getStorageSync('openid');
        searchallorderlist({
          openId: openId
        }).then(res => {
          //  console.log(res.data);
        }).catch(res => {
          //  console.log(res.data);
        })
      },
      goToOrderPage(type) {
        this.type = type; // 更新本地数据中的type
        uni.setStorageSync('orderType', type); // 将type存储到本
        // 跳转到订单页面，并传递订单类型
        uni.navigateTo({
          url: `/pages/order/order`
        });
      },
      goToAddressPage() {
        // 跳转到收货地址页面
        uni.navigateTo({
          url: '/pages/address/address'
        });
      },
      goToCustomerServicePage() {
        // 弹出客服电话
        getcostomer().then(res => {
          //  console.log(res.data);
          let phone = res.data.data[0].phone;
          let name = res.data.data[0].name;
          uni.showModal({
            title: `客服名称: ${name}`,
            content: `电话: ${phone}`,
            showCancel: true,
            cancelText: '取消',
            confirmText: '拨打电话',
            success: (res) => {
              if (res.confirm) {
                // If the user confirms, call the phone number
                uni.makePhoneCall({
                  phoneNumber: phone
                });
              } else if (res.cancel) {
                //  console.log('用户取消拨打电话');
              }
            }
          });
        }).catch(res => {
          //  console.log(res.data);
          uni.showToast({
            title: '获取客服信息失败',
            icon: 'none'
          });
        })
        uni.navigateTo({
          url: '/pages/customerService/customerService'
        });
      },
      goToSettingPage() {
        // 跳转到设置页面
        uni.navigateTo({
          url: '/pages/setting/setting'
        });
      },
      getpointscouponsInfo() {
        let userId = this.userId.toString();
        getpointscoupons(userId).then(res => {
          //  console.log(res.data.data);
          this.points = res.data.data.point;
          this.coupons = res.data.data.Coupons;
        }).catch(res => {
          //  console.log(res);
        })
      },
    },
    mounted() {
      i
      // this.getUserInfo();
      // this.searchorderinfo();
    },
    onLoad() {
      // this.getUserInfo();
      //   this.getOrderItems();
    },
    onShow() {
      // this.getpointscouponsInfo();
      this.getUserInfo();
    }
  };
</script>

<style scoped>
  .container {
    background-color: #f8f8f8;
    height: 100vh;
    padding: 0 3%;

  }

  .form {
    padding-bottom: 10px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    flex-wrap: nowrap;

  }

  .submitBtn {
    background-color: #2ba245;

  }

  .username {
    padding: 5rpx 0rpx;
    font-size: 28rpx;
    font-weight: bold;
    color: #333;

    box-sizing: content-box;
    display: flex;
    justify-content: center;

  }

  .user-info {
    background-color: #fff;
    border-radius: 16rpx;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    height: 300rpx;
    margin-bottom: 10px;
  }

  .user-info .button-reset::after {
    border: 1px solid #fff;
  }

  .user-info .button-reset {
    display: flex;
    appearance: none;
    /* 去掉默认样式 */
    background: none;
    /* 去掉背景 */
    padding: 0;
    /* 去掉内边距 */


    cursor: pointer;
    /* 保持指针样式 */
  }

  .user-picture {
    padding: 10px 0;
  }

  .avatar {
    width: 130rpx;
    height: 130rpx;
    border-radius: 50%;

    /*    border: 0.1px solid #666; */
  }

  .user-name {
    width: auto;
    display: flex;
    flex-direction: row;
    align-items: center;
    box-sizing: content-box;
    padding-bottom: 10px;
    justify-content: space-around;
  }

  .vip {
    display: flex;
    border-radius: 15px;
    padding: 7rpx 20rpx;
    background-color: #2ba245;
    color: #fff;
    margin-left: 10px;
    font-size: 28rpx;
  }

  .wallet {
    display: flex;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
  }

  .wallet-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    font-size: 28rpx;
    text-align: center;
  }

  .wallet-value {


    color: #ff4444;
  }

  .wallet-title {

    color: #666;
  }

  .order-section,
  .function-section {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
  }

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
  }

  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
  }

  .view-all {
    font-size: 28rpx;
    color: #666;
  }

  .order-types {
    display: flex;
    justify-content: space-around;
    align-items: center;
  }

  .order-type {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20rpx 0;
  }

  .order-icon {
    color: #666;
    margin-bottom: 10rpx;
  }

  .order-type-title {
    font-size: 28rpx;
    color: #666;
  }

  .order-type-number {
    font-size: 26rpx;
    color: #ff4444;
  }

  .function-section {
    margin-bottom: 0;
  }

  .function-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;
  }

  .function-item:last-child {
    border-bottom: none;
  }

  .function-icon {
    margin-right: 20rpx;
    color: #666;
  }

  .function-title {
    display: block;
    background-color: #fff;
    border-radius: 0;
    line-height: normal;
    text-align: left;
    flex-grow: 1;
    font-size: 14px;
    color: #333;
    padding: 0;
    /* margin: 10rpx; */
  }

  .function-title::after {
    border: none;
  }
</style>